package com.sugar.queryinfo.module.business.service.config;

import cn.hutool.core.collection.CollUtil;
import com.sugar.queryinfo.module.business.dal.dataobject.userbalancerecord.UserBalanceRecordDO;
import com.sugar.queryinfo.module.business.dal.mysql.userbalancerecord.UserBalanceRecordMapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import com.sugar.queryinfo.module.business.controller.admin.config.vo.*;
import com.sugar.queryinfo.module.business.dal.dataobject.config.BizConfigDO;
import com.sugar.queryinfo.framework.common.pojo.PageResult;
import com.sugar.queryinfo.framework.common.pojo.PageParam;
import com.sugar.queryinfo.framework.common.util.object.BeanUtils;

import com.sugar.queryinfo.module.business.dal.mysql.config.BizConfigMapper;

import static com.sugar.queryinfo.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.sugar.queryinfo.framework.common.util.collection.CollectionUtils.convertList;
import static com.sugar.queryinfo.framework.common.util.collection.CollectionUtils.diffList;
import static com.sugar.queryinfo.framework.common.util.date.DateUtils.FORMAT_YEAR_MONTH_DAY;
import static com.sugar.queryinfo.module.business.enums.ErrorCodeConstants.*;

/**
 * 参数配置 Service 实现类
 *
 * @author Ysugar
 */
@Service
@Validated
public class BizConfigServiceImpl implements BizConfigService {

    @Resource
    private BizConfigMapper bizConfigMapper;
    @Resource
    private UserBalanceRecordMapper userBalanceRecordMapper;

    @Override
    public Long createBizConfig(BizConfigSaveReqVO createReqVO) {
        // 插入
        BizConfigDO bizConfig = BeanUtils.toBean(createReqVO, BizConfigDO.class);
        bizConfigMapper.insert(bizConfig);

        // 返回
        return bizConfig.getId();
    }

    @Override
    public void updateBizConfig(BizConfigSaveReqVO updateReqVO) {
        // 校验存在
        validateBizConfigExists(updateReqVO.getId());
        // 更新
        BizConfigDO updateObj = BeanUtils.toBean(updateReqVO, BizConfigDO.class);
        bizConfigMapper.updateById(updateObj);
    }

    @Override
    public void deleteBizConfig(Long id) {
        // 校验存在
        validateBizConfigExists(id);
        // 删除
        bizConfigMapper.deleteById(id);
    }

    @Override
        public void deleteBizConfigListByIds(List<Long> ids) {
        // 删除
        bizConfigMapper.deleteByIds(ids);
        }


    private void validateBizConfigExists(Long id) {
        if (bizConfigMapper.selectById(id) == null) {
            throw exception(BIZ_CONFIG_NOT_EXISTS);
        }
    }

    @Override
    public BizConfigDO getBizConfig(Long id) {
        return bizConfigMapper.selectById(id);
    }

    @Override
    public PageResult<BizConfigDO> getBizConfigPage(BizConfigPageReqVO pageReqVO) {
        return bizConfigMapper.selectPage(pageReqVO);
    }

    @Override
    public HomeStatisticsRespVO homeStatistics() {
        HomeStatisticsRespVO respVO = new HomeStatisticsRespVO();

        // 总接口调用次数
        respVO.setSqCount(userBalanceRecordMapper.selectCount(UserBalanceRecordDO::getType, 0));
        // 今日登录次数
        LocalDateTime beginTime = LocalDate.now().atStartOfDay();
        respVO.setLoginCount(userBalanceRecordMapper.selectLoginCount(beginTime, LocalDateTime.now()));
        // 登录总次数
        respVO.setLoginTotalCount(userBalanceRecordMapper.selectLoginTotalCount());

        LocalDateTime localDateTime = beginTime.plusDays(-7);

        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern(FORMAT_YEAR_MONTH_DAY);

        // 获取开始日期
        LocalDate beginDate = localDateTime.toLocalDate();
        LocalDate nowDate = LocalDate.now();

        // 获取近一周每日的接口调用次数
        List<HomeStatisticsRespVO.Statistics> sqStatistics = userBalanceRecordMapper.selectSqStatistics(localDateTime);

        // 获取近一周每日的登录次数
        List<HomeStatisticsRespVO.Statistics> loginStatistics = userBalanceRecordMapper.selectLoginStatistics(localDateTime);

        do {
            String dateStr = beginDate.format(dateFormatter);
            boolean isNotExists = sqStatistics.stream().noneMatch(sq -> dateStr.equals(sq.getDate()));
            if (isNotExists) {
                HomeStatisticsRespVO.Statistics statistics = new HomeStatisticsRespVO.Statistics();
                statistics.setCount(0L).setDate(dateStr);
                sqStatistics.add(statistics);
            }
            boolean isNotExists2 = loginStatistics.stream().noneMatch(sq -> dateStr.equals(sq.getDate()));
            if (isNotExists2) {
                HomeStatisticsRespVO.Statistics statistics = new HomeStatisticsRespVO.Statistics();
                statistics.setCount(0L).setDate(dateStr);
                loginStatistics.add(statistics);
            }
            beginDate = beginDate.plusDays(1);
        }while (beginDate.isBefore(nowDate));

        respVO.setSqStatistics(sqStatistics.stream().sorted(Comparator.comparing(HomeStatisticsRespVO.Statistics::getDate)).collect(Collectors.toList()))
                .setLoginStatistics(loginStatistics.stream().sorted(Comparator.comparing(HomeStatisticsRespVO.Statistics::getDate)).collect(Collectors.toList()));

        return respVO;
    }

    @Override
    public AppGetConfigRespVO appGetConfig() {
        AppGetConfigRespVO respVO = new AppGetConfigRespVO();

        respVO.setUserManual(bizConfigMapper.selectById(8).getValue());
        respVO.setPrivacyPolicy(bizConfigMapper.selectById(9).getValue());

        return respVO;
    }

}